import { Button, DatePicker, Form, Icon, Input, Select, Table, notification } from 'antd';
import React, { Fragment } from 'react';
import _ from 'lodash';
// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router-dom';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import moment, { Moment } from 'moment';

import RepairDetailDialog from './components/detailDialog';
import CreateDetailDialog from './components/createDialog';
import DetailDialog from '../components/detailDialog';

import { getMerchant } from '../service';
import { setCommonFun } from '@/utils/tools';
import { getRepairColumns, addSign } from './utils';
import {
  checkShowOpt,
  getTableFiltersData,
  initialTimeWithMill,
  getErrTip,
  checkHasChanged,
  urlEncode,
} from '../utils';
import styles from './style.less';
import { checkPermission } from '@/utils/resolvePermission';
import { PAGE_SIZE_OPTION, SUCCESS_CODE } from '../data';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;
const orderPath = '/api/gl/recharge/manage/create/order';
const stormOrderPath = '/api/gl/recharge/manage/create/order/forStormPay';

interface StateType {
  [propName: string]: any;
}

interface PropType {
  [propName: string]: any;
}

// 初始化表头数据
function initTableFilters() {
  return {
    userType: '-1',
    orderStatus: '0,1,2,3,4,5,6', // 订单状态
  };
}

// 补单记录下拉数据改变
function repairStatusChange(val: number) {
  let str: string;
  switch (val) {
    case 1:
      str = '0,1,2,3,4,5,6';
      break;
    case 2:
      str = '2,3,4';
      break;
    default:
      break;
  }
  return str;
}

function openNotification(msg: string, description: string) {
  notification.open({
    message: msg,
    description,
    duration: null,
    icon: <Icon type="check-circle" style={{ color: '#108ee9' }} />,
  });
}

// 渲染表单
function renderFilters(self: any) {
  const { getFieldDecorator } = self.props.form;
  const { errTip, merchantList } = self.state;
  const tip = getErrTip(errTip);

  return (
    <Form layout="inline" onSubmit={self.handleSubmit}>
      {/* 提交时间 */}
      <FormItem
        label={<FormattedMessage id="recharge-repair-filters.commit-time" />}
        {...tip.timeTip}
      >
        {getFieldDecorator('time', {
          initialValue: initialTimeWithMill(3),
        })(
          <RangePicker
            showTime={{
              hideDisabledOptions: true,
              defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
            }}
            format="YYYY-MM-DD HH:mm:ss"
            placeholder={[
              formatMessage({ id: 'recharge-repair-filters.time-placeholder-start-time' }),
              formatMessage({ id: 'recharge-repair-filters.time-placeholder-end-time' }),
            ]}
            onChange={(dates: Moment[]) => {
              if (dates.length < 1 && !self.checkOrderId()) {
                self.setState({ errTip: true });
              }
              if (dates.length < 1 && !self.checkOrderId() && !errTip) {
                self.setState({ errTip: true });
              } else if ((dates.length > 0 || self.checkTime()) && errTip) {
                self.setState({ errTip: false });
              }
            }}
          />,
        )}
      </FormItem>

      {/* 充值单号 */}
      <FormItem
        label={<FormattedMessage id="recharge-repair-filters.order-id" />}
        {...tip.orderIdTip}
      >
        {getFieldDecorator('orderId', {
          initialValue: '',
        })(
          <Input
            placeholder={formatMessage({ id: 'recharge-repair-filters.order-id-placeholder' })}
            allowClear
            onChange={(e: any) => {
              const { value } = e.target;
              if (!value && !self.checkTime() && !errTip) {
                self.setState({ errTip: true });
              } else if ((value || self.checkTime()) && errTip) {
                self.setState({ errTip: false });
              }
            }}
          />,
        )}
      </FormItem>

      {/* 账户名 */}
      <FormItem label={<FormattedMessage id="recharge-repair-filters.user-name" />}>
        {getFieldDecorator('userName', {
          initialValue: '',
        })(
          <Input
            placeholder={formatMessage({ id: 'recharge-repair-filters.user-name-placeholder' })}
            allowClear
          />,
        )}
      </FormItem>

      {/* 充值类型 */}
      <FormItem label={<FormattedMessage id="recharge-repair-filters.recharge-type" />}>
        {getFieldDecorator('limitType', {
          initialValue: -1,
        })(
          <Select style={{ width: 120 }}>
            {/* 全部 */}
            <Option value={-1}>{formatMessage({ id: 'recharge-repair-filters.all' })}</Option>
            {/* 普通充值 */}
            <Option value={0}>
              {formatMessage({ id: 'recharge-repair-filters.recharge-type-normal' })}
            </Option>
            {/* 大额充值 */}
            <Option value={1}>
              {formatMessage({ id: 'recharge-repair-filters.recharge-type-large' })}
            </Option>
          </Select>,
        )}
      </FormItem>

      {/* 补单记录： */}
      <FormItem label={<FormattedMessage id="recharge-repair-filters.repair-record" />}>
        {getFieldDecorator('repairStatus', {
          initialValue: 1,
        })(
          <Select
            style={{ width: 120 }}
            onChange={(val: number) => {
              // const tableFilterData = setStatus(val);
              const { tableFilters } = self.state;
              const orderStatus = repairStatusChange(val);
              self.setState({ tableFilters: { ...tableFilters, orderStatus } });
            }}
          >
            {/* 全部 */}
            <Option value={1}>{formatMessage({ id: 'recharge-repair-filters.all' })}</Option>
            {/* 已补单 */}
            <Option value={2}>
              {formatMessage({ id: 'recharge-repair-filters.repair-record-complete' })}
            </Option>
          </Select>,
        )}
      </FormItem>

      <FormItem>
        {/* 搜索 */}
        <Button type="primary" htmlType="submit" disabled={errTip}>
          {formatMessage({ id: 'recharge-repair-filters.search-btn' })}
        </Button>
        {/* 重置 */}
        <Button style={{ marginLeft: '10px' }} onClick={self.handleReset}>
          {formatMessage({ id: 'recharge-repair-filters.reset-btn' })}
        </Button>
        {checkPermission(self.props.btns, 'new-finance-recharge-repair-create') ? (
          // 创建订单
          <Button style={{ marginLeft: '10px' }} onClick={self.handleCreate}>
            {formatMessage({ id: 'recharge-repair-filters.create-order-btn' })}
          </Button>
        ) : null}
      </FormItem>
    </Form>
  );
}

// 渲染表格
function renderTable(self: any) {
  const { loading } = self.state;
  const { size, page } = self.state.payload;
  const { repairData } = self.props.recharge;

  return (
    <Table
      loading={loading}
      className={styles.tableStyle}
      style={{ wordBreak: 'break-all' }}
      bordered
      rowKey={(record: any) => record.orderId}
      columns={getRepairColumns(self)}
      dataSource={repairData.list}
      onChange={self.handleChange}
      scroll={{ x: 1900, y: 540 }}
      pagination={{
        total: repairData.total,
        pageSize: size,
        current: page,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: PAGE_SIZE_OPTION,
        showTotal: () =>
          `共 ${repairData.total}条记录 第 ${page} / ${Math.ceil(repairData.total / size)}`,
      }}
    />
  );
}

@setCommonFun
class Repair extends React.PureComponent<PropType, StateType> {
  public state: StateType = {
    loading: false,
    payload: {
      size: 20,
      page: 1,
      dateType: 1, // 1 充值时间 2 到账时间
    },
    tableFilters: initTableFilters(),
    rowData: {},
    dialogVisible: false,
    isShowOpt: false,
    createDialogVisible: false,
    detailDialogVisible: false,
    isRepair: false,
    merchantList: [],
    errTip: false,
  };

  componentDidMount() {
    this.getMerchantList();
    this.getList();
  }

  // 表头的输入框搜索
  private getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ confirm }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          value={this.state.tableFilters[dataIndex]}
          onChange={e => {
            const state = _.cloneDeep(this.state);
            state.tableFilters[dataIndex] = e.target.value;
            this.setState({
              ...state,
            });
          }}
          onPressEnter={() => this.getList(confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
          allowClear
        />
        {/* 搜索 */}
        <Button
          type="primary"
          onClick={() => {
            const { payload } = this.state;
            this.setState({ payload: { ...payload, page: 1 } }, () => this.getList(confirm));
          }}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          {formatMessage({ id: 'recharge-repair-filters.search-btn' })}
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
  });

  // 获取表格数据
  private getList = (confirm?: any) => {
    if (confirm) confirm();
    const params = this.props.form.getFieldsValue();
    console.log('params', params);
    const { payload, tableFilters } = this.state;
    const tableFiltersData = _.cloneDeep(tableFilters);
    const sendData = this.setFiltersData(payload, tableFiltersData, params);
    delete sendData.repairStatus;
    this.bindEffects(sendData);
  };

  private bindEffects = (payload: object) => {
    this.setState({ loading: true });
    this.props.dispatch({
      type: 'recharge/repairDataEffect',
      payload,
      callback: () => {
        this.setState({ loading: false });
      },
    });
  };

  // 获取收款商户
  private getMerchantList = () => {
    getMerchant().then((res: any) => {
      if (res) {
        const { code, data } = res;
        if (code === SUCCESS_CODE && data) {
          this.setState({ merchantList: data });
        }
      }
    });
  };

  // 获取银行列表
  private getBankListEffect = (payload: object) => {
    this.props.dispatch({
      type: 'recharge/setWithdrawBankEffect',
      payload,
    });
  };

  // 创建订单 - 保存
  private createOrderEffect = (payload: object, isStorm: boolean) => {
    if (isStorm) {
      this.props.dispatch({
        type: 'recharge/repairCreateStormEffect',
        payload,
        callback: (response: { code: number; message: string; data: any }) => {
          const { code, data } = response;
          if (code === SUCCESS_CODE) {
            openNotification('创建订单成功', `订单号：${data.tradeNo}`);
            this.setState({ createDialogVisible: false });
            this.getList();
          }
        },
      });
      return;
    }

    const urlStr = urlEncode({
      ...payload,
      ...addSign(),
    }).substr(1);
    const path = isStorm ? stormOrderPath : orderPath;
    window.open(`${path}?${urlStr}`, '_blank');
    this.setState({ createDialogVisible: false });
    this.getList();
  };

  // 校验订单号
  private checkOrderId = () => this.props.form.getFieldValue('orderId').trim();

  // 校验是否选择时间
  private checkTime = () => {
    const timeValue = this.props.form.getFieldValue('time');
    return timeValue.length > 0;
  };

  // 表单提交
  private handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!this.checkOrderId() && !this.checkTime()) {
      this.setState({ errTip: true });
    } else {
      this.setState({ page: 1 }, () => {
        this.getList();
      });
    }
  };

  // 表单重置
  private handleReset = () => {
    this.props.form.resetFields();
    const payload = { page: 1, size: 20 };
    this.setState({ tableFilters: initTableFilters(), payload }, () => {
      this.getList();
    });
  };

  // 补单操作
  private handleDetail = (rowData: any) => {
    const isShowOpt = checkShowOpt(rowData);
    const { channelId } = rowData;
    if (channelId === 1001 || channelId === 1003) {
      this.getBankListEffect({ channelId: rowData.channelId, rechargeType: 0 });
    }
    this.setState({
      dialogVisible: true,
      rowData,
      isShowOpt,
      isRepair: true,
    });
  };

  // 关闭详情弹窗
  private handleDetailDialogClose = () => {
    this.setState({
      dialogVisible: false,
      rowData: {},
    });
  };

  // 打开创建订单弹窗
  private handleCreate = () => {
    this.setState({
      createDialogVisible: true,
    });
  };

  // 表格onChange
  private handleChange = (pagination, filters) => {
    const { tableFilters } = this.state;
    const { current, pageSize } = pagination;
    const tableFiltersData = getTableFiltersData(filters);
    const hasChanged = filters ? checkHasChanged(tableFilters, filters) : false;
    if (tableFiltersData.channelId) {
      tableFiltersData.channelId = Number(tableFiltersData.channelId);
    }
    if (!tableFiltersData.orderStatus) {
      tableFiltersData.orderStatus = initTableFilters().orderStatus;
    }
    const { payload } = this.state;
    const data = { ...payload, size: pageSize, page: hasChanged ? 1 : current };
    this.setState({ payload: data, tableFilters: { ...tableFilters, ...tableFiltersData } }, () => {
      this.getList();
    });
  };

  render() {
    const {
      dialogVisible,
      createDialogVisible,
      detailDialogVisible,
      rowData,
      isShowOpt,
    } = this.state;

    return (
      <Fragment>
        {renderFilters(this)}
        {renderTable(this)}
        {dialogVisible ? (
          <RepairDetailDialog<>
            visible={dialogVisible}
            data={rowData}
            showOpt={isShowOpt}
            confirm={() => {
              this.handleDetailDialogClose();
              this.getList();
            }}
            close={this.handleDetailDialogClose}
          />
        ) : null}
        {createDialogVisible ? (
          <CreateDetailDialog<>
            visible={createDialogVisible}
            cancle={() => {
              this.setState({ createDialogVisible: false });
            }}
            confirm={this.createOrderEffect}
          />
        ) : null}
        {detailDialogVisible ? (
          <DetailDialog<>
            visible={detailDialogVisible}
            rowData={rowData}
            close={() => this.setState({ detailDialogVisible: false, rowData: {} })}
          />
        ) : null}
      </Fragment>
    );
  }
}

const RepairContainer = Form.create({ name: 'rechargeRepair' })(Repair);

export default withRouter(
  connect(({ recharge, global }: { recharge: any; global: any }) => ({
    recharge,
    btns: global.btns,
  }))(RepairContainer),
);
